<template>
  <div class="app-container">
    <el-form class="alert-bar" :inline="true" label-width="120px">
      <el-form-item label="">
        <el-switch class="alert-switch"
                   disabled
                   v-model="alertInfo.isOpen"
                   active-color="#13ce66"
                   inactive-color="#ff4949"
                   active-text="开"
                   inactive-text="报警关">
        </el-switch>
      </el-form-item>
      <template v-if="alertInfo.isEdit">
        <el-form-item label="静默截止时间">
          <el-time-picker class="alert-input" clearable v-model="alertInfo.openTime"></el-time-picker>
        </el-form-item>
        <el-button type="primary" :disabled="!alertInfo.openTime" @click="editTime(alertInfo.openTime)">确认</el-button>
      </template>
      <template v-else>
        <el-form-item label="静默截止时间">
          {{`${alertInfo.openTime.getHours()}时${alertInfo.openTime.getMinutes()}分${alertInfo.openTime.getSeconds()}秒`}}
        </el-form-item>
        <el-button type="success" @click="alertInfo.isEdit = true">修改</el-button>
      </template>

      <el-form-item label="报警循环次数">
        <el-input-number :min="1" label="描述文字" v-model="alertInfo.alertTimes"></el-input-number>
      </el-form-item>
    </el-form>
    <el-row :gutter="20">
      <el-col :span="6" v-for="item in dataSourceList" :key="item.tbSourceId">
        <a href="javascript:;" @click="showDataList(item)">
          <el-card :body-style="{ padding: '0px' }" class="monitor-card" :class="formatDataSourceStatus(item)">
            <div slot="header" class="clearfix">
              <span>{{item.sourceName}}</span>
            </div>
            <div style="padding: 10px 14px;">
              <el-form>
                <el-form-item label="最后采集时间">
                  <div>{{item.lastTime || '(暂无)'}}</div>
                </el-form-item>
                <el-form-item label="本次采集条数">
                  <div>{{item.successCount || '0'}} 条</div>
                </el-form-item>
                <el-form-item label="本次更新条数">
                  <div>{{item.duplicatedCount || '0'}} 条</div>
                </el-form-item>
                <el-form-item label="当日采集条数">
                  <div>{{item.successCountSum || '0'}} 条</div>
                </el-form-item>
                <el-form-item label="当日更新条数">
                  <div>{{item.duplicatedCountSum || '0'}} 条</div>
                </el-form-item>
                <el-form-item label="最后采集状态">
                  <div>{{formatStatus(item.analysisStatus)}}</div>
                </el-form-item>
                <el-form-item label="上次执行时间">
                  <div>{{formatDuration(item.lastExecuteTime)}}</div>
                </el-form-item>
                <el-form-item label="今日最长执行时间">
                  <div>{{formatDuration(item.todayMaxExecuteTime)}}</div>
                </el-form-item>
                <el-form-item label="本日异常次数">
                  <div>{{item.errorCount || '0'}} 次</div>
                </el-form-item>
                <el-form-item label="今日执行总次数">
                  <div>{{item.todayExecuteCount || '0'}} 次</div>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </a>
      </el-col>
    </el-row>
    <el-dialog
      :title="listQuery.sourceName"
      :visible.sync="dialogVisible"
      width="90%"
    >
      <el-form :inline="true">
        <!--<el-form-item label="栏目">-->
        <!--<el-popover-->
        <!--v-model="visiblePopover"-->
        <!--placement="bottom-start"-->
        <!--trigger="click"-->
        <!--@show="filterText4 = ''"-->
        <!--&gt;-->
        <!--<el-input-->
        <!--placeholder="输入关键字进行过滤"-->
        <!--v-model="filterText4">-->
        <!--</el-input>-->
        <!--<el-tree-->
        <!--:filter-node-method="filterNode" :clearable="true"-->
        <!--ref="tree4" :props="props" :data="treeList" :highlight-current="false" node-key="code"-->
        <!--:default-expand-all="true" :render-content="renderContent"-->
        <!--&gt;-->
        <!--</el-tree>-->
        <!--<el-select-->
        <!--value-key='id' style="width: 250px" :clearable="true"-->
        <!--popper-class="hide" slot="reference" v-model="listQuery.cmsNewsClassId" type="text"-->
        <!--placeholder="请输入"-->
        <!--&gt;-->
        <!--<el-option-->
        <!--v-for="(item, index) in options" :key="item.value" :value="item.value" :label="item.label"-->
        <!--&gt;</el-option>-->
        <!--</el-select>-->
        <!--</el-popover>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="数据源名称">-->
        <!--<el-select v-model="listQuery.tbSourceId" :clearable="true">-->
        <!--<el-option v-for="(item, index) in options2" :key="item.id" :value="item.id"-->
        <!--:label="item.sourceName"></el-option>-->
        <!--</el-select>-->
        <!--</el-form-item>-->
        <el-form-item label="状态">
          <el-select v-model="listQuery.analysisStatus" clearable>
            <el-option value="0" label="正常"></el-option>
            <el-option value="1" label="异常"></el-option>
            <el-option value="2" label="运行中"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集开始时间">
          <el-date-picker :clearable="true" type="datetimerange" :default-time="['00:00:00', '23:59:59']"
                          @keyup.enter.native="getList" style="width: 450px;" class="filter-item"
                          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                          v-model="listQuery.updateTime" :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-button style="margin-bottom: 24px;"
                   class="filter-item" type="primary" icon="el-icon-search" @click="getList"
        >
          {{$t('table.search')}}
        </el-button>
        <el-switch
          style="float: right"
          v-model="switchValue"
          @change="getList"
          active-text="过滤数据"
          inactive-text="全量">
        </el-switch>
      </el-form>
      <el-table
        :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="加载中..." border fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column align="center" type="selection" width="55">
        </el-table-column>
        <el-table-column align="center" label="数据源名称">
          <template slot-scope="scope">
            <span>{{scope.row.sourceName}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="栏目">
          <template slot-scope="scope">
            <span>{{scope.row.cmsClassName}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="来源数据量">
          <template slot-scope="scope">
            <span>{{scope.row.queryCount}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="查询起始时间">
          <template slot-scope="scope">
            <span>{{scope.row.queryStartTime}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="查询终止时间">
          <template slot-scope="scope">
            <span>{{scope.row.queryEndTime}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="采集开始时间">
          <template slot-scope="scope">
            <span>{{scope.row.createTime}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="采集终止时间">
          <template slot-scope="scope">
            <span>{{scope.row.updateTime}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="采集时长">
          <template slot-scope="scope">
            <span>{{formatDuration(new Date(scope.row.updateTime).getTime()/1000 - new Date(scope.row.createTime).getTime()/1000)}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="运行情况">
          <template slot-scope="scope">
            <span>{{formatStatus(scope.row.analysisStatus)}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="异常原因">
          <template slot-scope="scope">
            <span>{{scope.row.analysisMessage}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="当前入库数据量">
          <template slot-scope="scope">
            <span>{{scope.row.successCount}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="更新条数">
          <template slot-scope="scope">
            <span>{{scope.row.duplicatedCount}}</span>
          </template>
        </el-table-column>
        <!--<el-table-column align="center" label="重复数据量">-->
        <!--<template slot-scope="scope">-->
        <!--<span>{{scope.row.duplicatedCount}}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column align="center" label="日志更新时间">
          <template slot-scope="scope">
            <span>{{scope.row.updateTime}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="listQuery.pageNum"
          :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total"
        >
        </el-pagination>
      </div>
      <!--<span slot="footer" class="dialog-footer">-->
      <!--<el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
      <!--</span>-->
    </el-dialog>

  </div>
</template>

<script>
  import {
    dataSourceMonitorList,
    dataSourceList,
    dataSourceMonitorCount,
    dataSourceMonitorAllList
  } from '../../api/data'
  import { listList } from '@/api/column'
  import { baseUrl } from '@/utils/request'
  import pinyin from 'pinyin'
  // import { Random } from 'mockjs'

  window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext
  const audioContext = new window.AudioContext()
  let soundSource, soundNode, songLength

  export default {
    name: 'complexTable',
    watch: {
      filterText1 (val) {
        this.$refs.tree1.filter(val)
      },
      filterText2 (val) {
        this.$refs.tree2.filter(val)
      },
      filterText3 (val) {
        this.$refs.tree3.filter(val)
      },
      filterText4 (val) {
        this.$refs.tree4.filter(val)
      }
    },
    data () {
      return {
        filterText1: '',
        filterText2: '',
        filterText3: '',
        filterText4: '',
        soundStartTime: new Date().getTime(),
        alertInfo: {
          isOpen: true,
          isEdit: true,
          openTime: 0,
          alertTimes: 5
        },
        props: {
          label: 'name',
          id: 'id',
          isLeaf (data) {
            return !data.child
          }
        },
        switchValue: true,
        tableKey: 0,
        list: null,
        count: null,
        total: null,
        listLoading: true,
        countLoading: true,
        visiblePopover: false,
        dialogVisible: false,
        listQuery: {
          pageNum: 1,
          pageSize: 20,
          cmsNewsClassId: '',
          tbSourceId: '',
          sourceName: '',
          analysisStatus: '',
          updateTime: [new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 24 * 3600 * 1000, new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000]
        },
        showReviewer: false,
        dbList: [],
        treeList: [{
          name: '栏目列表',
          id: 0,
          children: []
        }],
        options: [],
        options2: [],
        dataSourceList: [],
        temp: {
          id: '',
          cmsClassName: '',
          queryCount: '',
          queryEndTime: '',
          queryStartTime: '',
          sourceName: '',
          successCount: '',
          updateTime: ''
        },
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick (picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
              const start = end + 1000 - 3600 * 1000 * 24
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三天',
            onClick (picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
              const start = end + 1000 - 3600 * 1000 * 24 * 3
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick (picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
              const start = end + 1000 - 3600 * 1000 * 24 * 7
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    created () {
      const that = this
      const request = new XMLHttpRequest()
      request.open('GET', baseUrl + 'template/warning.mp3', true)
      request.responseType = 'arraybuffer'

      // Decode asynchronously
      request.onload = function () {
        audioContext.decodeAudioData(request.response, function (buffer) {
          soundSource = buffer
          songLength = buffer.duration
          const loopNode = function () {
            soundNode = audioContext.createBufferSource()
            soundNode.connect(audioContext.destination)
            soundNode.buffer = soundSource
            soundNode.loop = true
            soundNode.onended = loopNode
          }
          loopNode()
          that.getNodeList()
          that.getSourceList()
          that.getCount()
          that.interval = setInterval(() => that.getCount(), 10000)
          that.interval2 = setInterval(() => {
            if (!that.alertInfo.isEdit && that.alertInfo.openTime <= new Date()) {
              that.alertInfo.isOpen = true
            }
          }, 1000)
        })

      }
      request.send()
    },
    destroyed () {
      if (this.interval) clearInterval(this.interval)
      if (this.interval2) clearInterval(this.interval2)
    },
    methods: {
      formatDataSourceStatus (item) {
        const that = this
        let result = 'card-primary'
        if (item.analysisStatus === 1) result = 'card-danger'
        if (new Date(item.currentTime || '').getTime() > new Date(item.lastTime).getTime() + 1000 * 60 * 2) result = 'card-danger'
        if (item.errorCount > 0) result = 'card-warning'
        // console.log(`~~~~~~~~~~~~~~~~~~~~~~~~`)
        // console.log(this.notification)
        // console.log(soundSource)
        // console.log(this.alertInfo.isOpen)
        if (result === 'card-danger' && !this.notification && soundSource && this.alertInfo.isOpen) {
          this.notification = this.$notify({
            dangerouslyUseHTMLString: true,
            onClick: () => {
              this.notification.close()
            },
            onClose: () => {
              soundNode.stop()
              this.notification = false
            },
            title: '异常警报',
            message: '数据源异常，点击关闭报警',
            type: 'error',
            duration: 0
          })
          soundNode.start(0)
          setTimeout(function () {
            soundNode.stop()
            this.notification.close()
            this.notification = false
          }, songLength * 1000 * that.alertInfo.alertTimes)
        }
        return result
      },
      editTime (val) {
        this.alertInfo.isEdit = false
        if (val > new Date()) {
          this.alertInfo.isOpen = false
          if (this.notification) this.notification.close()
        }
      },
      formatDuration (val) {
        const hour = Math.floor(val / 3600)
        const minute = Math.floor(val / 60 - hour * 60)
        const second = Math.ceil(val - hour * 3600 - minute * 60)
        return (hour ? hour + ' 时 ' : '') + (minute ? minute + ' 分 ' : '') + second + ' 秒 '
      },
      formatStatus (val) {
        switch (val) {
          case 0:
            return '正常'
          case 1:
            return '异常'
          case 2:
            return '运行中'
          default:
            return '未知'
        }
      },
      filterNode (value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1 || pinyin(data.name, {
          style: pinyin.STYLE_FIRST_LETTER,
          heteronym: true
        }).join('').indexOf(value) !== -1
      },
      showDataList (item) {
        this.listQuery.tbSourceId = item.tbSourceId
        this.listQuery.sourceName = item.sourceName
        this.listQuery.pageNum = 1
        this.getList()
        this.dialogVisible = true
      },
      getList () {
        this.listLoading = true
        const params = {
          pageNum: this.listQuery.pageNum,
          pageSize: this.listQuery.pageSize,
          cmsNewsClassId: this.listQuery.cmsNewsClassId,
          tbSourceId: this.listQuery.tbSourceId,
          analysisStatus: this.listQuery.analysisStatus,
          startTime: this.listQuery.updateTime ? this.listQuery.updateTime[0] : '',
          endTime: this.listQuery.updateTime ? this.listQuery.updateTime[1] : ''
        }
        if (this.switchValue) {
          dataSourceMonitorList(params).then(response => {
            this.listLoading = false
            this.list = response.Data
            this.total = parseInt(response.total)
          })
        } else {
          dataSourceMonitorAllList(params).then(response => {
            this.listLoading = false
            this.list = response.Data
            this.total = parseInt(response.total)
          })
        }
      },
      getCount () {
        dataSourceMonitorCount({}).then(response => {
          this.dataSourceList = response.Data
        })
      },
      getSourceList () {
        const params = {
          pageNum: 1,
          pageSize: 99999
        }
        dataSourceList(params).then(response => {
          this.options2 = response.Data
        })
      },
      getNodeList () {
        listList({
          pageNum: 1,
          pageSize: 10000
        }).then(response => {
          const temp = {}
          const result = []
          const data = response.Data
          const length = data.length
          for (let i = 0; i < length; i++) {
            temp[data[i].id] = data[i]
            this.options.push({
              label: data[i].name,
              value: data[i].id
            })
          }
          for (let i = 0; i < length; i++) {
            if (temp[data[i].id].parentId && temp[data[i].parentId]) {
              if (!temp[data[i].parentId].children) {
                temp[data[i].parentId].children = []
              }
              temp[data[i].parentId].children.push(temp[data[i].id])
            } else {
              result.push(temp[data[i].id])
            }
          }
          this.treeList[0].children = result
        })
      },
      handleFilter () {
        this.listQuery.pageNum = 1
        this.getList()
      },
      handleSizeChange (val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange (val) {
        this.listQuery.pageNum = val
        this.getList()
      },
      handleModifyStatus (row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      resetTemp () {
        this.temp = {
          id: '',
          cmsClassName: '',
          queryCount: '',
          queryEndTime: '',
          queryStartTime: '',
          sourceName: '',
          successCount: '',
          updateTime: ''
        }
      },
      renderContent (h, {node, data, store}) {
        return (
          <span class={(node.isLeaf && node.level > 1) ? 'custom-tree-node' : 'custom-tree-node custom-tree-notLeaf'}>
            <span className='tree-label'>{node.label}&nbsp;</span>
            <span>
              {(node.level > 1 && node.isLeaf) ? <el-button
                size='mini' type='text'
                on-click={() => {
                  {
                    this.visiblePopover = false
                    this.listQuery.cmsNewsClassId = data.id
                  }
                }}
              >选择</el-button> : ''}
            </span>
          </span>
        )
      }
    }
  }
</script>

<style lang="scss">
  .alert-bar {
    .alert-switch {
      opacity: 1;
      height: 24px;
    }
  }

  .hide {
    display: none;
  }

  .el-popover {
    overflow-x: hidden;
    overflow-y: auto;
    max-height: 600px;
  }

  .nowrap {
    white-space: nowrap;
  }

  .el-tooltip__popper {
    max-width: 50%;
  }

  .monitor-card {
    &:hover, &:focus {
      box-shadow: 0 0 20px #999;
    }
    margin-bottom: 20px;
    .el-card__body {
      .el-form-item {
        margin-bottom: 0 !important;
      }
      .el-form-item--medium .el-form-item__content, .el-form-item--medium .el-form-item__label {
        line-height: 24px;
      }
    }
  }
</style>
